﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;
using WebSocketServer.WebSocketService.Interface;
using WebSocketServer.WebSocketService.Plugins;

namespace WebSocketServer.WebSocketService
{
    public class WebSocketServerService : IHostedService
    {
    
        private readonly ILogger<WebSocketServerService> _logger;
        private HttpService _service;

        public WebSocketServerService(ILogger<WebSocketServerService> logger)
        {
            _logger = logger;
        }

      

       

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _service = new HttpService();
            await _service.SetupAsync(new TouchSocketConfig()
                .SetListenIPHosts(8081)
                .ConfigureContainer(a =>
                {
                    a.AddConsoleLogger(); // 可替换为适配ILogger的实现
                })
                .ConfigurePlugins(a =>
                {
                    a.UseWebSocket()
                     .SetWSUrl("/ws")
                     .UseAutoPong();
                     //.SetVerifyConnection(VerifyConnection); // 可添加验证连接的插件，如验证token等
                    a.Add<RecieveMessagePlugin>();
                    a.Add<MyWebSocketConnectionPlugin>();
                }));
            await _service.StartAsync();

            _logger.LogInformation("WebSocket服务器已启动，地址 ws://127.0.0.1:8081/ws");
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            if (_service != null)
            {
                await _service.StopAsync();
                _logger.LogInformation("WebSocket服务器已停止");
            }
        }


        /// <summary>
        /// 验证websocket的连接
        /// </summary>
        /// <param name="client"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private static bool VerifyConnection(IHttpSessionClient client, HttpContext context)
        {
            if (!context.Request.IsUpgrade())//如果不包含升级协议的header，就直接返回false。
            {
                return false;
            }
            if (context.Request.UrlEquals("/ws"))//以此连接，则直接可以连接
            {
                return true;
            }
            else if (context.Request.UrlEquals("/wsquery"))//以此连接，则需要传入token才可以连接
            {
                if (context.Request.Query.Get("token") == "123456")
                {
                    return true;
                }
                else
                {
                    context.Response
                        .SetStatus(403, "token不正确")
                        .AnswerAsync();
                }
            }
            else if (context.Request.UrlEquals("/wsheader"))//以此连接，则需要从header传入token才可以连接
            {
                if (context.Request.Headers.Get("token") == "123456")
                {
                    return true;
                }
                else
                {
                    context.Response
                        .SetStatus(403, "token不正确")
                        .AnswerAsync();
                }
            }
            return false;
        }
    }
}
